﻿using System;
using System.Linq;
using System.Security.Cryptography;
using Grundy.Common;

namespace Grundy.CryptographicServices
{
    public class Sha256MacProvider : CustomerCryptographicServicesProvider
    {   
        private HMACSHA256 _selfProvider;
        private const string SHA256MACPROVIDER = "Sha256MacProvider";

        public Sha256MacProvider(string selfKey, Guid customerId = default(Guid), string customerName = null)
            : base(selfKey)
        {
            _customerId = customerId;
            _customerName = customerName;
            _selfProvider = new HMACSHA256(selfKey.ToByteArray());
        }

        public Sha256MacProvider(byte[] selfKey, Guid customerId = default(Guid), string customerName = null)
            : base(string.Empty)
        {
            _customerId = customerId;
            _customerName = customerName;
            _selfProvider = new HMACSHA256(selfKey);
        }

        public override string Algorithm
        {
            get { return _selfProvider.HashName; }
        }

        public override string Provider
        {
            get
            {
                return "{0},{1},{2}".FormatWith(SHA256MACPROVIDER, _customerId, _customerName);
            }
        }

        protected override byte[] SignData(byte[] data)
        {
            return _selfProvider.ComputeHash(data);
        }

        protected override bool VerifyData(byte[] data, byte[] signature)
        {
            return _selfProvider.ComputeHash(data).SequenceEqual(signature);
        }

        public override byte[] EncryptData(byte[] data)
        {
            throw new NotImplementedException();
        }

        public override byte[] DecryptData(byte[] data)
        {
            throw new NotImplementedException();
        }

        public override bool CanVerifyProvider(string providerString)
        {
            var info = (providerString ?? string.Empty).Split(new[] {','});
            return info[0].EqualsIgnoreCase(SHA256MACPROVIDER);
        }

        public override Guid CustomerId
        {
            get { return _customerId; }
        }

        public override string CustomerName
        {
            get { return _customerName; }
        }
    }
}